from datetime import datetime, timedelta

import jwt
from flask_redis import FlaskRedis

from cfg.model.UserModel import UserModel

secret_key_str = "dashdwqe0hno123dalsdk90123maslnxdio"
expiration_time_in_seconds = 60 * 60 * 2
redis = FlaskRedis()


# 生成Token
def generate_token(data: UserModel):
    date = data.join_time
    if isinstance(date, datetime):
        date = date.isoformat()
    redis.setex(date, data.id, expiration_time_in_seconds)  # 存储 Token 到 Redis，并设置过期时间
    return jwt.encode(payload={
        "id": data.id,
        "username": data.username,
        "email": data.email
    }, key=secret_key_str, algorithm='HS256')


# 验证Token
def verify_token(token_str):
    try:
        data = jwt.decode(token_str, secret_key_str, algorithms=['HS256'])
        val = redis.get(data.id)
        if not val:
            return None
        else:
            expiration_time = redis.pttl(data.id)
            if expiration_time > 0:
                # 刷新token
                if expiration_time < expiration_time_in_seconds / 2:
                    redis.setex(val, data.id, expiration_time_in_seconds)  # 存储 Token 到 Redis，并设置过期时间
                return val
            else:
                return None
    except jwt.ExpiredSignatureError:
        # Token已过期
        return None
    except jwt.InvalidTokenError:
        # Token无效
        return None
